{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Biome Level statistics for model: SD2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import the libraries\n",
    "import ee\n",
    "import pandas as pd\n",
    "import os\n",
    "import numpy as np\n",
    "import random\n",
    "from random import sample\n",
    "import itertools \n",
    "import geopandas as gpd\n",
    "from sklearn.metrics import r2_score\n",
    "from termcolor import colored # this is allocate colour and fonts type for the print title and text\n",
    "from IPython.display import display, HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#set the working directory of local drive for Grid search result table loading\n",
    "# os.getcwd()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# initialize the earth engine API\n",
    "ee.Initialize()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1 Load the required composites and images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the basic maps that needed for the analysis\n",
    "# load the carbon concentration map\n",
    "carbonConcentration = ee.Image(\"users/leonidmoore/ForestBiomass/Biome_level_Wood_Carbon_Conentration_Map\")\n",
    "# load the root shoot ratio map\n",
    "rootShootRatio = ee.Image(\"users/leonidmoore/ForestBiomass/Root_shoot_ratio_Map\").unmask()\n",
    "# load the two composites tha will be used in the analysis\n",
    "compositeImage =ee.Image(\"users/leonidmoore/ForestBiomass/20200915_Forest_Biomass_Predictors_Image\")\n",
    "compositeImageNew = ee.Image(\"projects/crowtherlab/Composite/CrowtherLab_Composite_30ArcSec\")\n",
    "# load the biome layer \n",
    "biomeLayer = compositeImage.select(\"WWF_Biome\")\n",
    "# define a pixel area layer with unit km2\n",
    "pixelAreaMap = ee.Image.pixelArea().divide(10000);\n",
    "# define the boundary geography reference\n",
    "unboundedGeo = ee.Geometry.Polygon([-180, 88, 0, 88, 180, 88, 180, -88, 0, -88, -180, -88], None, False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2 Load the biomass density maps"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the carbon density layers\n",
    "potentialDensity = ee.Image(\"users/nordmannmoore/ForestBiomass/RemoteSensingModel/EnsambleMaps/Predicted_SD2_Potential_density_Ensambled_Mean\").unmask()\n",
    "presentDensity =  ee.Image(\"users/leonidmoore/ForestBiomass/RemoteSensingModel/ESA_CCI_AGB_Map_bias_corrected_1km_2010\").unmask().multiply(carbonConcentration)\n",
    "\n",
    "# define the standard projection\n",
    "stdProj = potentialDensity.projection();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3 Adjust the present and potential density maps"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the present and potential forest cover\n",
    "presentForestCover = compositeImage.select('PresentTreeCover').unmask() # uniform with potential in the  0-1 scale\n",
    "potentialCoverAdjusted = ee.Image(\"users/leonidmoore/ForestBiomass/Bastin_et_al_2019_Potential_Forest_Cover_Adjusted\").unmask().rename('PotentialForestCover')\n",
    "# define the present and potential forest cover masks\n",
    "presentMask= presentForestCover.gt(0)\n",
    "potentialMask= potentialCoverAdjusted.gt(0)\n",
    "\n",
    "# check the difference of the two density maps\n",
    "potentialHigher = potentialDensity.multiply(pixelAreaMap).subtract(presentDensity.multiply(pixelAreaMap)).gte(0)\n",
    "potentialLower = potentialDensity.multiply(pixelAreaMap).subtract(presentDensity.multiply(pixelAreaMap)).lt(0)\n",
    "# replace the lower potential value by present biomass density value\n",
    "agbPotentialDensity = presentDensity.multiply(potentialLower).add(potentialDensity.multiply(potentialHigher))\n",
    "# add the root biomass to the AGB to get TGB\n",
    "tgbPotentialDensity = agbPotentialDensity.multiply(rootShootRatio).add(agbPotentialDensity)\n",
    "tgbPresentDensity = presentDensity.multiply(rootShootRatio).add(presentDensity)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4 Partioning the potential cover into different landuse types"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load all the landuse type layers\n",
    "croplandOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/cropland_Percent\").rename('cropland').divide(100).reproject(crs=stdProj);\n",
    "grazingOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/grazing_Percent\").rename('grazing').divide(100).reproject(crs=stdProj);\n",
    "pastureOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/pasture_Percent\").rename('pasture').divide(100).reproject(crs=stdProj);\n",
    "rangelandOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/rangeland_Percent\").rename('rangeland').divide(100).reproject(crs=stdProj);\n",
    "urbanOrg = compositeImage.select(['LandCoverClass_Urban_Builtup']).divide(100).unmask().reproject(crs=stdProj);\n",
    "snowIceOrg = compositeImageNew.select(['ConsensusLandCoverClass_Snow_Ice']).divide(100).unmask().reproject(crs=stdProj);\n",
    "openWaterOrg = compositeImageNew.select(['ConsensusLandCoverClass_Open_Water']).divide(100).unmask().reproject(crs=stdProj);\n",
    "# define the total landcover types\n",
    "sumCover = presentForestCover.add(pastureOrg).add(rangelandOrg).add(croplandOrg).add(urbanOrg).add(openWaterOrg).add(snowIceOrg);\n",
    "oneSubtract = ee.Image(1).subtract(sumCover);\n",
    "freeland = oneSubtract.multiply(oneSubtract.gte(0));\n",
    "# get the scale ratio for pixels with sumCover larger than 1\n",
    "scaleRatio = ee.Image(1).subtract(presentForestCover).divide(sumCover.subtract(presentForestCover)).multiply(oneSubtract.lt(0));\n",
    "# get the ratio of these three disturbed maps\n",
    "pasture = pastureOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(pastureOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "rangeland = rangelandOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(rangelandOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "cropland = croplandOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(croplandOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "urban = urbanOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(urbanOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "openWater = openWaterOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(openWaterOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "snowIce = snowIceOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(snowIceOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "sumTT = presentForestCover.add(pasture).add(rangeland).add(cropland).add(urban).add(freeland).add(openWater).add(snowIce).unmask();\n",
    "\n",
    "effectivePotentialMask = freeland.add(rangeland).add(pasture).add(cropland).add(urban).gt(0);\n",
    "# there are some pixels without any landcover survived but with open water and ice and snow. here we mask these pixels out\n",
    "sumlandCover = pastureOrg.add(rangelandOrg).add(croplandOrg).add(urbanOrg).add(freeland);\n",
    "restorationMap = potentialCoverAdjusted.subtract(presentForestCover).mask(effectivePotentialMask).unmask();\n",
    "\n",
    "# sum all these scaled layersv\n",
    "scaledSum = pasture.add(rangeland).add(cropland).add(urban).add(freeland);\n",
    "potentialCoverFinal = restorationMap.add(presentForestCover);\n",
    "# allocate the potential equally to each layer\n",
    "freelandPotentialCover = freeland.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "rangelandPotentialCover = rangeland.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "pasturePotentialCover = pasture.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "croplandPotentialCover = cropland.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "urbanPotentialCover = urban.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "#  allocate the freeland potential in pixels with forest cover larger than 10% to conservation potential\n",
    "freelandForConsevation = freelandPotentialCover.multiply(presentForestCover.gte(0.1)).unmask();\n",
    "maximumPotentialCover = freelandForConsevation.add(presentForestCover);\n",
    "# calucate the reall freeland outside of forest\n",
    "freelandLeftMap = freelandPotentialCover.subtract(freelandForConsevation).unmask()# the left positive pixels are real freeland pixels"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5 Partioning the biomass potential into different landuse types"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# calculate the existing carbon, present potential carbon and absolute potential carbon in forests\n",
    "absoluteImage1 = tgbPresentDensity.multiply(pixelAreaMap).multiply(presentMask).divide(1000000000).rename('Present')\n",
    "absoluteImage3 = tgbPotentialDensity.multiply(pixelAreaMap).multiply(potentialCoverFinal.gt(0)).divide(1000000000).rename('AbsolutePotential')\n",
    "# get the sum of the potential covers\n",
    "potentialCoverSum = freelandLeftMap.add(rangelandPotentialCover).add(pasturePotentialCover).add(croplandPotentialCover).add(urbanPotentialCover)\n",
    "\n",
    "trueRestorationPotential = absoluteImage3.subtract(absoluteImage1).multiply(1000000000)\n",
    "ratioPotentialBiomassDensity = absoluteImage1.multiply(potentialCoverFinal.divide(presentForestCover))\n",
    "#  get the real for conservation potential\n",
    "realDensityIncreased = absoluteImage3.subtract(absoluteImage1).mask(absoluteImage3.subtract(ratioPotentialBiomassDensity).gt(0)).unmask()\n",
    "realDensityNotIncreased = absoluteImage3.subtract(absoluteImage1).mask(absoluteImage3.subtract(ratioPotentialBiomassDensity).lte(0)).unmask()\n",
    "trueReforestationPotential = realDensityNotIncreased.add(realDensityIncreased.multiply(ee.Image(1).subtract(presentForestCover.divide(potentialCoverFinal))))\n",
    "\n",
    "conservationPotentialPart1 = realDensityIncreased.multiply(presentForestCover.add(freelandForConsevation).divide(potentialCoverFinal))\n",
    "conservationPotentialPart2 = realDensityNotIncreased.multiply(freelandForConsevation.divide(potentialCoverFinal.subtract(presentForestCover)))\n",
    "\n",
    "# calculate the part of the potential inside the forest cover which was allocate to conservation potential.\n",
    "freelandForConservation1 = realDensityIncreased.multiply(freelandForConsevation.divide(potentialCoverFinal))\n",
    "freelandForConservation = freelandForConservation1.add(conservationPotentialPart2).rename('FreeToConservation')\n",
    "\n",
    "absoluteImage2 = conservationPotentialPart1.add(conservationPotentialPart2).add(absoluteImage1).rename('PresentPotential')\n",
    "\n",
    "trueReforestationPotential = absoluteImage3.subtract(absoluteImage2)\n",
    "\n",
    "absoluteImage4 = trueReforestationPotential.multiply(freelandLeftMap.divide(potentialCoverSum)).rename('FreelandPotential')\n",
    "absoluteImage5 = trueReforestationPotential.multiply(rangelandPotentialCover.divide(potentialCoverSum)).rename('RangelandPotential')\n",
    "absoluteImage6 = trueReforestationPotential.multiply(pasturePotentialCover.divide(potentialCoverSum)).rename('PasturePotential')\n",
    "absoluteImage7 = trueReforestationPotential.multiply(croplandPotentialCover.divide(potentialCoverSum)).rename('CroplandPotential')\n",
    "absoluteImage8 = trueReforestationPotential.multiply(urbanPotentialCover.divide(potentialCoverSum)).rename('UrbanPotential')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Calculate the potential numbers and write into local folder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[34mThe biomass partition results in biome: \n",
      "\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Present</th>\n",
       "      <th>PresentPotential</th>\n",
       "      <th>AbsolutePotential</th>\n",
       "      <th>FreelandPotential</th>\n",
       "      <th>RangelandPotential</th>\n",
       "      <th>PasturePotential</th>\n",
       "      <th>CroplandPotential</th>\n",
       "      <th>UrbanPotential</th>\n",
       "      <th>FreeToConservation</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>186.488539</td>\n",
       "      <td>224.949428</td>\n",
       "      <td>246.906764</td>\n",
       "      <td>4.087479</td>\n",
       "      <td>0.081286</td>\n",
       "      <td>7.821893</td>\n",
       "      <td>9.716738</td>\n",
       "      <td>0.249940</td>\n",
       "      <td>6.510934</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>6.459329</td>\n",
       "      <td>9.285510</td>\n",
       "      <td>16.478155</td>\n",
       "      <td>1.770447</td>\n",
       "      <td>0.021341</td>\n",
       "      <td>1.797035</td>\n",
       "      <td>3.558535</td>\n",
       "      <td>0.045287</td>\n",
       "      <td>0.636881</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2.530593</td>\n",
       "      <td>3.694014</td>\n",
       "      <td>4.600505</td>\n",
       "      <td>0.306483</td>\n",
       "      <td>0.024783</td>\n",
       "      <td>0.344041</td>\n",
       "      <td>0.227944</td>\n",
       "      <td>0.003242</td>\n",
       "      <td>0.339726</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>45.220397</td>\n",
       "      <td>55.846069</td>\n",
       "      <td>74.213937</td>\n",
       "      <td>4.128202</td>\n",
       "      <td>0.025749</td>\n",
       "      <td>5.528918</td>\n",
       "      <td>8.271928</td>\n",
       "      <td>0.413072</td>\n",
       "      <td>3.198553</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>23.560230</td>\n",
       "      <td>26.823789</td>\n",
       "      <td>29.609613</td>\n",
       "      <td>1.213942</td>\n",
       "      <td>0.044786</td>\n",
       "      <td>0.928726</td>\n",
       "      <td>0.563492</td>\n",
       "      <td>0.034878</td>\n",
       "      <td>1.409091</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>57.746120</td>\n",
       "      <td>69.755036</td>\n",
       "      <td>73.881403</td>\n",
       "      <td>3.675197</td>\n",
       "      <td>0.001210</td>\n",
       "      <td>0.246775</td>\n",
       "      <td>0.191340</td>\n",
       "      <td>0.011845</td>\n",
       "      <td>4.796681</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>38.736434</td>\n",
       "      <td>61.938697</td>\n",
       "      <td>99.348222</td>\n",
       "      <td>8.673790</td>\n",
       "      <td>12.878724</td>\n",
       "      <td>9.096184</td>\n",
       "      <td>6.695306</td>\n",
       "      <td>0.065520</td>\n",
       "      <td>4.597754</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>5.378404</td>\n",
       "      <td>6.818053</td>\n",
       "      <td>25.956358</td>\n",
       "      <td>3.579352</td>\n",
       "      <td>6.340274</td>\n",
       "      <td>2.518886</td>\n",
       "      <td>6.610255</td>\n",
       "      <td>0.089538</td>\n",
       "      <td>0.265292</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>1.496285</td>\n",
       "      <td>2.550333</td>\n",
       "      <td>3.774081</td>\n",
       "      <td>0.360570</td>\n",
       "      <td>0.414551</td>\n",
       "      <td>0.237152</td>\n",
       "      <td>0.202455</td>\n",
       "      <td>0.009021</td>\n",
       "      <td>0.128398</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>2.963950</td>\n",
       "      <td>5.083188</td>\n",
       "      <td>11.405564</td>\n",
       "      <td>1.775236</td>\n",
       "      <td>2.869552</td>\n",
       "      <td>0.846620</td>\n",
       "      <td>0.819838</td>\n",
       "      <td>0.011130</td>\n",
       "      <td>0.252023</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>5.279083</td>\n",
       "      <td>8.681657</td>\n",
       "      <td>13.734794</td>\n",
       "      <td>5.044882</td>\n",
       "      <td>0.001602</td>\n",
       "      <td>0.000597</td>\n",
       "      <td>0.005730</td>\n",
       "      <td>0.000327</td>\n",
       "      <td>0.481820</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>2.799836</td>\n",
       "      <td>4.549361</td>\n",
       "      <td>10.137652</td>\n",
       "      <td>1.493769</td>\n",
       "      <td>0.021149</td>\n",
       "      <td>1.917485</td>\n",
       "      <td>2.084093</td>\n",
       "      <td>0.071795</td>\n",
       "      <td>0.400118</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>1.813424</td>\n",
       "      <td>3.389765</td>\n",
       "      <td>32.093929</td>\n",
       "      <td>13.796449</td>\n",
       "      <td>11.073943</td>\n",
       "      <td>1.084931</td>\n",
       "      <td>2.681206</td>\n",
       "      <td>0.067634</td>\n",
       "      <td>0.312770</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>1.338357</td>\n",
       "      <td>2.110598</td>\n",
       "      <td>2.512605</td>\n",
       "      <td>0.140411</td>\n",
       "      <td>0.001349</td>\n",
       "      <td>0.080087</td>\n",
       "      <td>0.168496</td>\n",
       "      <td>0.011664</td>\n",
       "      <td>0.126457</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>sum</th>\n",
       "      <td>381.810981</td>\n",
       "      <td>485.475497</td>\n",
       "      <td>644.653583</td>\n",
       "      <td>50.046210</td>\n",
       "      <td>33.800298</td>\n",
       "      <td>32.449330</td>\n",
       "      <td>41.797355</td>\n",
       "      <td>1.084892</td>\n",
       "      <td>23.456497</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        Present  PresentPotential  AbsolutePotential  FreelandPotential  \\\n",
       "0    186.488539        224.949428         246.906764           4.087479   \n",
       "1      6.459329          9.285510          16.478155           1.770447   \n",
       "2      2.530593          3.694014           4.600505           0.306483   \n",
       "3     45.220397         55.846069          74.213937           4.128202   \n",
       "4     23.560230         26.823789          29.609613           1.213942   \n",
       "5     57.746120         69.755036          73.881403           3.675197   \n",
       "6     38.736434         61.938697          99.348222           8.673790   \n",
       "7      5.378404          6.818053          25.956358           3.579352   \n",
       "8      1.496285          2.550333           3.774081           0.360570   \n",
       "9      2.963950          5.083188          11.405564           1.775236   \n",
       "10     5.279083          8.681657          13.734794           5.044882   \n",
       "11     2.799836          4.549361          10.137652           1.493769   \n",
       "12     1.813424          3.389765          32.093929          13.796449   \n",
       "13     1.338357          2.110598           2.512605           0.140411   \n",
       "sum  381.810981        485.475497         644.653583          50.046210   \n",
       "\n",
       "     RangelandPotential  PasturePotential  CroplandPotential  UrbanPotential  \\\n",
       "0              0.081286          7.821893           9.716738        0.249940   \n",
       "1              0.021341          1.797035           3.558535        0.045287   \n",
       "2              0.024783          0.344041           0.227944        0.003242   \n",
       "3              0.025749          5.528918           8.271928        0.413072   \n",
       "4              0.044786          0.928726           0.563492        0.034878   \n",
       "5              0.001210          0.246775           0.191340        0.011845   \n",
       "6             12.878724          9.096184           6.695306        0.065520   \n",
       "7              6.340274          2.518886           6.610255        0.089538   \n",
       "8              0.414551          0.237152           0.202455        0.009021   \n",
       "9              2.869552          0.846620           0.819838        0.011130   \n",
       "10             0.001602          0.000597           0.005730        0.000327   \n",
       "11             0.021149          1.917485           2.084093        0.071795   \n",
       "12            11.073943          1.084931           2.681206        0.067634   \n",
       "13             0.001349          0.080087           0.168496        0.011664   \n",
       "sum           33.800298         32.449330          41.797355        1.084892   \n",
       "\n",
       "     FreeToConservation  \n",
       "0              6.510934  \n",
       "1              0.636881  \n",
       "2              0.339726  \n",
       "3              3.198553  \n",
       "4              1.409091  \n",
       "5              4.796681  \n",
       "6              4.597754  \n",
       "7              0.265292  \n",
       "8              0.128398  \n",
       "9              0.252023  \n",
       "10             0.481820  \n",
       "11             0.400118  \n",
       "12             0.312770  \n",
       "13             0.126457  \n",
       "sum           23.456497  "
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Stack the absolute biomass layers into an Image.\n",
    "absPotentialImage = absoluteImage1.addBands(absoluteImage2).addBands(absoluteImage3).addBands(absoluteImage4).addBands(absoluteImage5).addBands(absoluteImage6).addBands(absoluteImage7).addBands(absoluteImage8).addBands(freelandForConservation)\n",
    "# define the function to do the biome level statistics which could be applied by map      \n",
    "def biomeLevelStat(biome):\n",
    "    biomeMask = biomeLayer.eq(ee.Number(biome))\n",
    "    masked_img = absPotentialImage.mask(biomeMask)\n",
    "    output = masked_img.reduceRegion(reducer= ee.Reducer.sum(),\n",
    "                                     geometry= unboundedGeo,\n",
    "                                     crs='EPSG:4326',\n",
    "                                     crsTransform=[0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                     maxPixels= 1e13)\n",
    "    return output#.getInfo().get('Present')\n",
    "\n",
    "\n",
    "biomeList = ee.List([1,2,3,4,5,6,7,8,9,10,11,12,13,14])\n",
    "statisticTable = biomeList.map(biomeLevelStat).getInfo()\n",
    "# transform into data frame\n",
    "outputTable = pd.DataFrame(statisticTable,columns =['Present','PresentPotential','AbsolutePotential','FreelandPotential','RangelandPotential','PasturePotential','CroplandPotential','UrbanPotential','FreeToConservation'])#.round(1)\n",
    "outputTable.loc['sum'] = outputTable.sum() \n",
    "outputTable.to_csv('Data/BiomeLevelStatistics/StatisticsForModels/SD2_Biome_Level_Statistics.csv',header=True,mode='w+')\n",
    "# display the output of the carbon partitioning\n",
    "print(colored('The biomass partition results in biome: \\n', 'blue', attrs=['bold']))\n",
    "outputTable.head(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If you got the error 'EEException: Too many concurrent aggregations.', please re-run this chunck of code again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[34mThe biomass partition results in biome: \n",
      "\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Present</th>\n",
       "      <th>PresentPotential</th>\n",
       "      <th>AbsolutePotential</th>\n",
       "      <th>FreelandPotential</th>\n",
       "      <th>RangelandPotential</th>\n",
       "      <th>PasturePotential</th>\n",
       "      <th>CroplandPotential</th>\n",
       "      <th>UrbanPotential</th>\n",
       "      <th>FreeToConservation</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>227.523114</td>\n",
       "      <td>274.449710</td>\n",
       "      <td>301.240898</td>\n",
       "      <td>4.987326</td>\n",
       "      <td>0.099510</td>\n",
       "      <td>9.543874</td>\n",
       "      <td>11.855551</td>\n",
       "      <td>0.304927</td>\n",
       "      <td>7.943953</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>7.880397</td>\n",
       "      <td>11.328311</td>\n",
       "      <td>20.103673</td>\n",
       "      <td>2.159978</td>\n",
       "      <td>0.026245</td>\n",
       "      <td>2.192508</td>\n",
       "      <td>4.341380</td>\n",
       "      <td>0.055250</td>\n",
       "      <td>0.776986</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3.088217</td>\n",
       "      <td>4.507793</td>\n",
       "      <td>5.613757</td>\n",
       "      <td>0.373935</td>\n",
       "      <td>0.030199</td>\n",
       "      <td>0.419701</td>\n",
       "      <td>0.278173</td>\n",
       "      <td>0.003956</td>\n",
       "      <td>0.414580</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>60.141477</td>\n",
       "      <td>74.269544</td>\n",
       "      <td>98.695493</td>\n",
       "      <td>5.489170</td>\n",
       "      <td>0.034191</td>\n",
       "      <td>7.352771</td>\n",
       "      <td>11.000514</td>\n",
       "      <td>0.549303</td>\n",
       "      <td>4.252992</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>31.333880</td>\n",
       "      <td>35.673379</td>\n",
       "      <td>39.375922</td>\n",
       "      <td>1.613299</td>\n",
       "      <td>0.059177</td>\n",
       "      <td>1.234746</td>\n",
       "      <td>0.748958</td>\n",
       "      <td>0.046363</td>\n",
       "      <td>1.873724</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>103.902230</td>\n",
       "      <td>125.506619</td>\n",
       "      <td>132.928616</td>\n",
       "      <td>6.612753</td>\n",
       "      <td>0.002026</td>\n",
       "      <td>0.443265</td>\n",
       "      <td>0.342699</td>\n",
       "      <td>0.021253</td>\n",
       "      <td>8.630686</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>47.259514</td>\n",
       "      <td>75.565701</td>\n",
       "      <td>121.205790</td>\n",
       "      <td>10.582061</td>\n",
       "      <td>15.712356</td>\n",
       "      <td>11.097502</td>\n",
       "      <td>8.168232</td>\n",
       "      <td>0.079937</td>\n",
       "      <td>5.609214</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>7.153926</td>\n",
       "      <td>9.068678</td>\n",
       "      <td>34.520605</td>\n",
       "      <td>4.760117</td>\n",
       "      <td>8.431347</td>\n",
       "      <td>3.349887</td>\n",
       "      <td>8.791500</td>\n",
       "      <td>0.119076</td>\n",
       "      <td>0.352877</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>1.826047</td>\n",
       "      <td>3.112136</td>\n",
       "      <td>4.605360</td>\n",
       "      <td>0.439959</td>\n",
       "      <td>0.505746</td>\n",
       "      <td>0.289403</td>\n",
       "      <td>0.247097</td>\n",
       "      <td>0.011019</td>\n",
       "      <td>0.156694</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>3.935717</td>\n",
       "      <td>6.750267</td>\n",
       "      <td>15.152684</td>\n",
       "      <td>2.358863</td>\n",
       "      <td>3.814129</td>\n",
       "      <td>1.125130</td>\n",
       "      <td>1.089499</td>\n",
       "      <td>0.014796</td>\n",
       "      <td>0.334711</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>9.499304</td>\n",
       "      <td>15.622517</td>\n",
       "      <td>24.716546</td>\n",
       "      <td>9.079186</td>\n",
       "      <td>0.002872</td>\n",
       "      <td>0.001074</td>\n",
       "      <td>0.010310</td>\n",
       "      <td>0.000587</td>\n",
       "      <td>0.867006</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>3.388736</td>\n",
       "      <td>5.506270</td>\n",
       "      <td>12.269168</td>\n",
       "      <td>1.807701</td>\n",
       "      <td>0.025692</td>\n",
       "      <td>2.320496</td>\n",
       "      <td>2.522120</td>\n",
       "      <td>0.086889</td>\n",
       "      <td>0.484296</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>2.194913</td>\n",
       "      <td>4.102516</td>\n",
       "      <td>38.838802</td>\n",
       "      <td>16.695350</td>\n",
       "      <td>13.401104</td>\n",
       "      <td>1.313280</td>\n",
       "      <td>3.244704</td>\n",
       "      <td>0.081848</td>\n",
       "      <td>0.378543</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>1.632809</td>\n",
       "      <td>2.574945</td>\n",
       "      <td>3.065391</td>\n",
       "      <td>0.171295</td>\n",
       "      <td>0.001644</td>\n",
       "      <td>0.097713</td>\n",
       "      <td>0.205564</td>\n",
       "      <td>0.014230</td>\n",
       "      <td>0.154277</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>sum</th>\n",
       "      <td>510.760280</td>\n",
       "      <td>648.038385</td>\n",
       "      <td>852.332704</td>\n",
       "      <td>67.130992</td>\n",
       "      <td>42.146239</td>\n",
       "      <td>40.781350</td>\n",
       "      <td>52.846302</td>\n",
       "      <td>1.389435</td>\n",
       "      <td>32.230539</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        Present  PresentPotential  AbsolutePotential  FreelandPotential  \\\n",
       "0    227.523114        274.449710         301.240898           4.987326   \n",
       "1      7.880397         11.328311          20.103673           2.159978   \n",
       "2      3.088217          4.507793           5.613757           0.373935   \n",
       "3     60.141477         74.269544          98.695493           5.489170   \n",
       "4     31.333880         35.673379          39.375922           1.613299   \n",
       "5    103.902230        125.506619         132.928616           6.612753   \n",
       "6     47.259514         75.565701         121.205790          10.582061   \n",
       "7      7.153926          9.068678          34.520605           4.760117   \n",
       "8      1.826047          3.112136           4.605360           0.439959   \n",
       "9      3.935717          6.750267          15.152684           2.358863   \n",
       "10     9.499304         15.622517          24.716546           9.079186   \n",
       "11     3.388736          5.506270          12.269168           1.807701   \n",
       "12     2.194913          4.102516          38.838802          16.695350   \n",
       "13     1.632809          2.574945           3.065391           0.171295   \n",
       "sum  510.760280        648.038385         852.332704          67.130992   \n",
       "\n",
       "     RangelandPotential  PasturePotential  CroplandPotential  UrbanPotential  \\\n",
       "0              0.099510          9.543874          11.855551        0.304927   \n",
       "1              0.026245          2.192508           4.341380        0.055250   \n",
       "2              0.030199          0.419701           0.278173        0.003956   \n",
       "3              0.034191          7.352771          11.000514        0.549303   \n",
       "4              0.059177          1.234746           0.748958        0.046363   \n",
       "5              0.002026          0.443265           0.342699        0.021253   \n",
       "6             15.712356         11.097502           8.168232        0.079937   \n",
       "7              8.431347          3.349887           8.791500        0.119076   \n",
       "8              0.505746          0.289403           0.247097        0.011019   \n",
       "9              3.814129          1.125130           1.089499        0.014796   \n",
       "10             0.002872          0.001074           0.010310        0.000587   \n",
       "11             0.025692          2.320496           2.522120        0.086889   \n",
       "12            13.401104          1.313280           3.244704        0.081848   \n",
       "13             0.001644          0.097713           0.205564        0.014230   \n",
       "sum           42.146239         40.781350          52.846302        1.389435   \n",
       "\n",
       "     FreeToConservation  \n",
       "0              7.943953  \n",
       "1              0.776986  \n",
       "2              0.414580  \n",
       "3              4.252992  \n",
       "4              1.873724  \n",
       "5              8.630686  \n",
       "6              5.609214  \n",
       "7              0.352877  \n",
       "8              0.156694  \n",
       "9              0.334711  \n",
       "10             0.867006  \n",
       "11             0.484296  \n",
       "12             0.378543  \n",
       "13             0.154277  \n",
       "sum           32.230539  "
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "deadWoodLitterRatio = ee.Image(\"users/leonidmoore/ForestBiomass/DeadWoodLitter/DeadWood_Litter_Ratio_Map\").unmask()\n",
    "\n",
    "# Stack the absolute biomass layers into an Image.\n",
    "absPotentialImage = absoluteImage1.addBands(absoluteImage2).addBands(absoluteImage3).addBands(absoluteImage4).addBands(absoluteImage5).addBands(absoluteImage6).addBands(absoluteImage7).addBands(absoluteImage8).addBands(freelandForConservation)\n",
    "# define the function to do the biome level statistics which could be applied by map      \n",
    "def biomeLevelStat(biome):\n",
    "    biomeMask = biomeLayer.eq(ee.Number(biome))\n",
    "    masked_img = absPotentialImage.mask(biomeMask).multiply(deadWoodLitterRatio)\n",
    "    output = masked_img.reduceRegion(reducer= ee.Reducer.sum(),\n",
    "                                     geometry= unboundedGeo,\n",
    "                                     crs='EPSG:4326',\n",
    "                                     crsTransform=[0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                     maxPixels= 1e13)\n",
    "    return output#.getInfo().get('Present')\n",
    "\n",
    "\n",
    "biomeList = ee.List([1,2,3,4,5,6,7,8,9,10,11,12,13,14])\n",
    "statisticTable = biomeList.map(biomeLevelStat).getInfo()\n",
    "# transform into data frame\n",
    "outputTable = pd.DataFrame(statisticTable,columns =['Present','PresentPotential','AbsolutePotential','FreelandPotential','RangelandPotential','PasturePotential','CroplandPotential','UrbanPotential','FreeToConservation'])#.round(1)\n",
    "outputTable.loc['sum'] = outputTable.sum()\n",
    "outputTable.to_csv('Data/BiomeLevelStatistics/StatisticsForModels/SD2_Biome_Level_Statistics_with_Litter.csv',header=True,mode='w+')\n",
    "# display the output of the carbon partitioning\n",
    "print(colored('The biomass partition results in biome: \\n', 'blue', attrs=['bold']))\n",
    "outputTable.head(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
